<script lang="ts">
  import type { RigidBody as RapierRigidBody } from '@dimforge/rapier3d-compat'
  import { T, useTask } from '@threlte/core'
  import { AutoColliders, Collider, RigidBody } from '@threlte/rapier'
  import { Color } from 'three'
  import TestBed from './TestBed.svelte'

  const gray = new Color(0x333333)
  const brand = new Color(0xff3f00)

  let present = $state(false)

  let rigidBody = $state.raw<RapierRigidBody>()
  const offset = Date.now()

  useTask(() => {
    const positionZ = Math.sin(Date.now() / 2000) * 2.5
    const positionX = Math.sin((Date.now() + offset) / 1500) * 1.2
    rigidBody?.setNextKinematicTranslation({ x: positionX, y: 1, z: positionZ })
  })
</script>

<!-- SENSOR -->
<T.Group position={[0, 1, 0]}>
  <Collider
    onsensorenter={() => (present = true)}
    onsensorexit={() => (present = false)}
    sensor
    shape="cuboid"
    args={[1, 1, 1]}
  />
</T.Group>

<T.Group position={[0, 1, 0]}>
  <RigidBody
    bind:rigidBody
    type="kinematicPosition"
    lockRotations
  >
    <AutoColliders shape="ball">
      <T.Mesh castShadow>
        <T.SphereGeometry />
        <T.MeshStandardMaterial color={present ? brand : gray} />
      </T.Mesh>
    </AutoColliders>
  </RigidBody>
</T.Group>

<TestBed title="Sensor Collider">
  {#snippet text()}
    <div>
      <p>
        This collider is marked as a sensor and as such does<br />
        not participate in contacts and collisions and can be<br />
        useful to detect presence in areas.
      </p>
    </div>
  {/snippet}
</TestBed>
